package com.learning.platform.controller;

import com.learning.platform.dto.*;
import com.learning.platform.enums.ExamStatus;
import com.learning.platform.enums.QuestionType;
import com.learning.platform.security.UserPrincipal;
import com.learning.platform.service.ExamService;
import com.learning.platform.service.QuestionBankService;
import jakarta.validation.Valid;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/v1/exams")
public class ExamController {
    
    private final ExamService examService;
    private final QuestionBankService questionBankService;
    
    public ExamController(ExamService examService, QuestionBankService questionBankService) {
        this.examService = examService;
        this.questionBankService = questionBankService;
    }
    
    // 题库管理
    @PostMapping("/questions")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<QuestionBankResponse> createQuestion(@Valid @RequestBody QuestionBankRequest request,
                                                           Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        QuestionBankResponse response = questionBankService.createQuestion(request, principal);
        return ApiResponse.success(response, "题目创建成功");
    }
    
    @PutMapping("/questions/{id}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<QuestionBankResponse> updateQuestion(@PathVariable Long id,
                                                           @Valid @RequestBody QuestionBankRequest request,
                                                           Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        QuestionBankResponse response = questionBankService.updateQuestion(id, request, principal);
        return ApiResponse.success(response, "题目更新成功");
    }
    
    @DeleteMapping("/questions/{id}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Void> deleteQuestion(@PathVariable Long id, Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        questionBankService.deleteQuestion(id, principal);
        return ApiResponse.success(null, "题目删除成功");
    }
    
    @GetMapping("/questions/{id}")
    public ApiResponse<QuestionBankResponse> getQuestion(@PathVariable Long id) {
        QuestionBankResponse response = questionBankService.getQuestion(id);
        return ApiResponse.success(response);
    }
    
    @GetMapping("/courses/{courseId}/questions")
    public ApiResponse<Page<QuestionBankResponse>> getQuestionsByCourse(
            @PathVariable Long courseId,
            @RequestParam(required = false) QuestionType questionType,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        
        Page<QuestionBankResponse> questions = questionBankService.getQuestionsByCourse(
            courseId, questionType, null, keyword, PageRequest.of(page - 1, pageSize));
        return ApiResponse.success(questions);
    }
    
    @GetMapping("/questions/search")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Page<QuestionBankResponse>> searchQuestions(
            @RequestParam(required = false) Long courseId,
            @RequestParam(required = false) QuestionType questionType,
            @RequestParam(required = false) String difficulty,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        
        Page<QuestionBankResponse> questions = questionBankService.searchQuestions(
            courseId, questionType, difficulty, keyword, PageRequest.of(page - 1, pageSize));
        return ApiResponse.success(questions);
    }
    
    // 考试管理
    @PostMapping
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<ExamResponse> createExam(@Valid @RequestBody ExamRequest request, Authentication auth) {
        if (auth == null || auth.getPrincipal() == null || !(auth.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        ExamResponse response = examService.createExam(request, principal);
        return ApiResponse.success(response, "考试创建成功");
    }
    
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<ExamResponse> updateExam(@PathVariable Long id,
                                               @Valid @RequestBody ExamRequest request,
                                               Authentication auth) {
        if (auth == null || auth.getPrincipal() == null || !(auth.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        ExamResponse response = examService.updateExam(id, request, principal);
        return ApiResponse.success(response, "考试更新成功");
    }
    
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Void> deleteExam(@PathVariable Long id, Authentication auth) {
        if (auth == null || auth.getPrincipal() == null || !(auth.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        examService.deleteExam(id, principal);
        return ApiResponse.success(null, "考试删除成功");
    }
    
    @GetMapping("/{id}")
    public ApiResponse<ExamResponse> getExam(@PathVariable Long id, Authentication auth) {
        ExamResponse response = examService.getExam(id);
        return ApiResponse.success(response);
    }
    
    @GetMapping("/search")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Page<ExamResponse>> searchExams(
            @RequestParam(required = false) Long courseId,
            @RequestParam(required = false) String examType,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            Authentication auth) {
        
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        Page<ExamResponse> exams = examService.searchExams(
            courseId, examType, status, keyword, 
            PageRequest.of(page - 1, pageSize), principal);
        return ApiResponse.success(exams);
    }
    
    @PostMapping("/{id}/publish")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Void> publishExam(@PathVariable Long id, Authentication auth) {
        if (auth == null || auth.getPrincipal() == null || !(auth.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        examService.publishExam(id, principal);
        return ApiResponse.success(null, "考试发布成功");
    }
    
    @PostMapping("/{id}/archive")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Void> archiveExam(@PathVariable Long id, Authentication auth) {
        if (auth == null || auth.getPrincipal() == null || !(auth.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        examService.archiveExam(id, principal);
        return ApiResponse.success(null, "考试归档成功");
    }
    
    @PostMapping("/{id}/copy")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<ExamResponse> copyExam(@PathVariable Long id, Authentication auth) {
        if (auth == null || auth.getPrincipal() == null || !(auth.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        ExamResponse response = examService.copyExam(id, principal);
        return ApiResponse.success(response, "复制成功");
    }
    
    @GetMapping("/courses/{courseId}")
    public ApiResponse<Page<ExamResponse>> getExamsByCourse(
            @PathVariable Long courseId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            Authentication auth) {
        
        // 允许匿名访问，学生只能看到已发布的考试
        Page<ExamResponse> exams = examService.getExamsByCourse(
            courseId, null, ExamStatus.PUBLISHED, PageRequest.of(page - 1, pageSize));
        return ApiResponse.success(exams);
    }
    
    @GetMapping("/{id}/stats")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<ExamStatsResponse> getExamStats(@PathVariable Long id, Authentication auth) {
        ExamStatsResponse response = examService.getExamStats(id);
        return ApiResponse.success(response);
    }

    @GetMapping("/{id}/trend")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<java.util.List<ExamTrendPoint>> getExamTrend(
            @PathVariable Long id,
            @RequestParam(defaultValue = "14") int days,
            Authentication auth) {
        return ApiResponse.success(examService.getExamDailyTrend(id, Math.max(1, Math.min(days, 90))));
    }
    
    // 考试答题
    @PostMapping("/{id}/start")
    public ApiResponse<ExamRecordResponse> startExam(@PathVariable Long id, Authentication auth) {
        if (auth == null || auth.getPrincipal() == null || !(auth.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        ExamRecordResponse response = examService.startExam(id, principal);
        return ApiResponse.success(response, "考试开始");
    }
    
    @GetMapping("/{examId}/questions")
    public ApiResponse<List<QuestionBankResponse>> getExamQuestions(@PathVariable Long examId, Authentication auth) {
        if (auth == null || auth.getPrincipal() == null || !(auth.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        List<QuestionBankResponse> questions = examService.getExamQuestions(examId, principal);
        return ApiResponse.success(questions);
    }
    
    @PostMapping("/submit")
    public ApiResponse<ExamRecordResponse> submitExam(@Valid @RequestBody ExamSubmitRequest request,
                                                     Authentication auth) {
        if (auth == null || auth.getPrincipal() == null || !(auth.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        ExamRecordResponse response = examService.submitExam(request, principal);
        return ApiResponse.success(response, "考试提交成功");
    }
    
    @GetMapping("/records/{recordId}")
    public ApiResponse<ExamRecordResponse> getExamRecord(@PathVariable Long recordId, Authentication auth) {
        ExamRecordResponse response = examService.getExamRecord(recordId);
        return ApiResponse.success(response);
    }
    
    @GetMapping("/records/{recordId}/answers")
    public ApiResponse<List<ExamAnswerResponse>> getExamAnswers(@PathVariable Long recordId, Authentication auth) {
        if (auth == null || auth.getPrincipal() == null || !(auth.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        List<ExamAnswerResponse> answers = examService.getExamAnswers(recordId, principal);
        return ApiResponse.success(answers);
    }
    
    @GetMapping("/my-records")
    public ApiResponse<Page<ExamRecordResponse>> getMyExamRecords(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            Authentication auth) {
        if (auth == null || auth.getPrincipal() == null || !(auth.getPrincipal() instanceof UserPrincipal)) {
            return ApiResponse.error(401, "用户未认证");
        }
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        Page<ExamRecordResponse> records = examService.getUserExamRecords(
            principal.getUserId(), PageRequest.of(page - 1, pageSize));
        return ApiResponse.success(records);
    }
}

